package com.bub.pay.core.util;

import java.security.MessageDigest;
import java.util.Base64;

public class SignUtil {
    public static final String SIGN_WITH_MD5 = "MD5";
    public static final String SIGN_WITH_SHA1 = "SHA-1";
    public static final String SIGN_WITH_SHA2 = "SHA-256";



    /**
     *
     * @param data
     * @param signType MD5   SHA
     * @return
     */
    public static String sign(String data , String signType) throws Exception{
        byte[] dataBytes = data.getBytes();
        MessageDigest messageDigest = MessageDigest.getInstance(signType);
        byte[] digest = messageDigest.digest(dataBytes);
//        System.out.println("base64:" + Base64.getEncoder().encodeToString(digest));
        String signature = bytesToHex(digest);
        return signature;
    }

    public static String signWithSalt(){

        return "";
    }

    /**
     * byte[] 转小写16进制
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes){
        StringBuffer sb = new StringBuffer();
        for(byte b : bytes){
            String hex = Integer.toHexString(b & 0xff);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }

        return sb.toString();
    }

    /**
     * byte[] 转大写16进制
     * @param bytes
     * @return
     */
    public static String bytesToUpperHex(byte[] bytes){
        return bytesToHex(bytes).toUpperCase();
    }

    public static void main(String[] args) throws Exception{
        String data = "test";
        System.out.println(sign(data,SIGN_WITH_MD5));
        System.out.println(sign(data,SIGN_WITH_SHA1));
        System.out.println(sign(data,SIGN_WITH_SHA2));

        System.out.println(bytesToHex(new byte[]{127,-127,1}));
    }
}
